package com.yueya.basic.menu;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.yueya.common.model.Tree;
import com.yueya.common.util.UUIDGenerator;

public class MenuService {

	/**
	 * 保存
	 * 
	 * @param menu
	 * @return
	 */
	@Before(Tx.class)
	public boolean saveMenu(Menu menu) {
		boolean bl = false;
		if (menu != null && menu.getStr("id") != null
				&& !"".equals(menu.getStr("id"))) {
			if (menu.getStr("parent_id").equals("root")) {// 根节点
				menu.set("is_leaf", "1");
			} else {
				menu.set("is_leaf", "0");
			}
			bl = menu.update();
		} else {
			String id = UUIDGenerator.getUUID();
			menu.set("id", id);
			if (menu.getStr("parent_id").equals("root")) {// 根节点
				menu.set("parent_id", id);
				menu.set("is_leaf", "1");
			} else {
				menu.set("is_leaf", "0");
			}
			bl = menu.save();
		}

		return bl;
	}

	/**
	 * 逻辑删除
	 * 
	 * @param id
	 * @return
	 */
	@Before(Tx.class)
	public boolean removeMenu(String id) {
		Menu menu = Menu.dao.findById(id);
		boolean bl;
		if (menu.get("id").equals(menu.get("parent_id"))) {
			int count = Menu.service.delMenuByPid(id);
			bl = count > 0 ? true : false;
		} else {
			int count = Menu.service.delMenuById(id);
			bl = count > 0 ? true : false;
		}
		return bl;
	}

	/**
	 * 获取菜单tree
	 * 
	 * @return
	 */
	public List<Tree> toTree() {
		List<Tree> list = new ArrayList<Tree>();
		Tree tree = rootTree();
		tree.setChildren(menuToTree(getRootMenu(), getChildMenu()));
		list.add(tree);
		return list;
	}

	// 获取菜单grid
	public List<Menu> toGrid() {

		return getRootMenu();
	}

	// 获取子菜单grid
	public List<Menu> toGridById(String pid) {
		List<Menu> list = null;
		String sql = " select * from t_menu where parent_id = ? and id <> parent_id order by order_id ";
		list = Menu.dao.find(sql, pid);
		return list;
	}

	// 获取下拉框tree
	@Deprecated
	public List<Tree> treeOfSelect() {
		List<Tree> rootList = new ArrayList<Tree>();
		Tree rootTree = rootTree();
		List<Tree> tempList = new ArrayList<Tree>();
		List<Menu> list = null;
		String sql = " select * from t_menu where id = parent_id order by order_id ";
		list = Menu.dao.find(sql);
		for (Menu menu : list) {
			Tree tree = singleMenuToTree(menu);
			tempList.add(tree);
		}
		rootTree.setChildren(tempList);
		rootList.add(rootTree);
		return rootList;
	}

	// 获取最大排序
	public int getMaxOrder(String pid) {
		StringBuffer sb = new StringBuffer();
		sb.append(" select order_id from t_menu where 1=1 ");
		if (pid.equals("root")) {
			sb.append(" and id = parent_id ");
			sb.append(" order by order_id desc limit 1,1 ");
		} else {
			sb.append(" and parent_id ='" + pid + "'");
			sb.append(" and parent_id != id ");
			sb.append(" order by order_id desc limit 1 ");
		}
		Menu menu = Menu.dao.findFirst(sb.toString());
		if (menu == null)
			return 0;
		else
			return menu.getInt("order_id");
	}

	// 通过父节点删除菜单
	public int delMenuByPid(String pid) {
		int count = 0;
		String sql = " delete from t_menu where parent_id = ? ";
		count = Db.update(sql, pid);
		return count;
	}

	// 通过子节点删除菜单
	public int delMenuById(String id) {
		int count = 0;
		String sql = " delete from t_menu where id = ? ";
		count = Db.update(sql, id);
		return count;
	}

	public List<Menu> getRootMenu() {
		List<Menu> root = null;
		StringBuffer sb = new StringBuffer();
		sb.append(" select * from t_menu where id = '000'  order by order_id ");
		root = Menu.dao.find(sb.toString());
		return root;
	}

	public List<Menu> getChildMenu() {
		List<Menu> child = null;
		StringBuffer sb = new StringBuffer();
		sb.append(" select * from t_menu where id <> parent_id  order by order_id ");
		child = Menu.dao.find(sb.toString());
		return child;
	}

	public List<Tree> menuToTree(List<Menu> root, List<Menu> child) {
		List<Tree> treeList = new ArrayList<Tree>();
		for (Menu menu : root) {
			Tree tree = singleMenuToTree(menu);
			List<Tree> tempList = new ArrayList<Tree>();
			for (Menu temp : child) {
				if (menu.getStr("id").equals(temp.getStr("parent_id"))) {
					Tree treeTemp = singleMenuToTree(temp);
					tempList.add(treeTemp);
				}
			}
			tree.setChildren(tempList);
			treeList.add(tree);
		}
		return treeList;
	}

	public Tree singleMenuToTree(Menu menu) {
		Tree tree = new Tree();
		tree.setId(menu.getStr("id"));
		tree.setPid(menu.getStr("parent_id"));
		tree.setText(menu.getStr("name"));
		tree.setIconCls(menu.getStr("icon"));
		tree.setChecked(false);
		tree.setState("open");
		tree.setAttributes(menu);
		return tree;
	}

	/**
	 * 根菜单
	 * 
	 * @return
	 */
	public Tree rootTree() {
		Tree tree = new Tree();
		tree.setId("root");
		tree.setPid("root");
		tree.setText("菜单");
		tree.setIconCls("mqw_xzmk_ico");
		tree.setState("open");
		return tree;
	}

	// 获取上一个菜单
	public Menu getUpMenu(Menu menu) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select * from t_menu where 1=1 ");
		if (menu.get("id").equals(menu.get("parent_id")))
			sql.append(" and id = parent_id ");
		else
			sql.append(" and parent_id = '" + menu.get("parent_id") + "' ");
		sql.append(" and order_id < '" + menu.getInt("order_id") + "' ");
		sql.append(" order by order_id desc ");
		Menu temp = Menu.dao.findFirst(sql.toString());
		return temp;
	}

	// 获取下一个菜单
	public Menu getDownMenu(Menu menu) {
		StringBuffer sql = new StringBuffer();
		sql.append(" select * from t_menu where 1=1 ");
		if (menu.get("id").equals(menu.get("parent_id")))
			sql.append(" and id = parent_id ");
		else
			sql.append(" and parent_id = '" + menu.get("parent_id") + "' ");
		sql.append(" and order_id > '" + menu.getInt("order_id") + "' ");
		sql.append(" order by order_id ");
		Menu temp = Menu.dao.findFirst(sql.toString());
		return temp;
	}

	public List<Menu> getMenuList(Map<String, Object> map) {
		String sql = "select * from t_menu where status = '1' ";
		if (map.get("level") != null && "1".equals(map.get("level"))) {
			sql += " and parent_id = id ";
		}
		if (map.get("level") != null && "2".equals(map.get("level"))) {
			sql += " and parent_id != id ";
		}
		sql += " order by order_id asc";
		return Menu.dao.find(sql);

	}

	public List<Menu> getMenuOneList(Map<String, Object> map) {
		String sql = " select * from t_menu a  join (select  c.parent_id   from t_role_user a join t_role_menu b on a.role_id=b.role_id join t_menu c on c.id=b.menu_id where   (a.user_id=? or exists (select 1 from t_role where is_mr='1' and id=a.role_id)) group by c.parent_id ) as b on a.id=b.parent_id where a.status='1' order by a.order_id asc ";
		System.out.println(sql);
		return Menu.dao.find(sql, (String) map.get("userid"));
	}

	public List<Menu> getMenuTwoList(Map<String, Object> map) {
		String sql = "select  c.* from t_role_user a join t_role_menu b on a.role_id=b.role_id join t_menu c on c.id=b.menu_id where   (a.user_id=? or exists (select 1 from t_role where is_mr='1' and id=a.role_id)) group by b.menu_id order by c.order_id asc";
		return Menu.dao.find(sql, (String) map.get("userid"));
	}

	
	public Tree recursiveTree(String cid) {
		// 根据cid获取节点对象(SELECT * FROM tb_tree t WHERE t.cid=?)
		Tree node = getTreeNode(cid);
		// 查询cid下的所有子节点(SELECT * FROM tb_tree t WHERE t.pid=?)
		List<Tree> childTreeNodes = queryTreeNode(cid);
		// System.out.print(childTreeNodes.size());
		// 遍历子节点
		if (childTreeNodes != null && childTreeNodes.size() > 0) {
			for (Tree child : childTreeNodes) {

				Tree n = recursiveTree(child.getId()); // 递归
				node.getChildren().add(n);

			}
		}

		return node;
	}
	
	public Tree getTreeNode(String cid) {
		Menu category = Menu.dao
				.findFirst(" select * from  t_menu where id = '"
						+ cid + "' ");
		Tree root = new Tree();
		root.setId(category.getStr("id"));
		if (cid == "000") {
			root.setIconCls("icon-wlkj-organ");
		} else {
			root.setIconCls("icon-wlkj-dept");
			if (Menu.service.isleaf(cid)) {
				root.setState("open");
			} else {
				root.setState("closed");
			}

		}

		root.setPid(category.getStr("parent_id"));
		root.setText(category.getStr("name"));

		return root;
	}
	
	public List<Tree> queryTreeNode(String pid) {
		List<Menu> list = Menu.dao
				.find(" select * from  t_menu where parent_id = '"
						+ pid + "' order by order_id asc");
		List<Tree> treeList = null;
		Tree root = null;
		Menu d = null;
		if (list != null && list.size() > 0) {
			treeList = new ArrayList<Tree>();
			for (int i = 0; i < list.size(); i++) {
				root = new Tree();
				d = list.get(i);
				root.setId(d.getStr("id"));
				root.setIconCls("icon-wlkj-dept");
				root.setPid(d.getStr("parent_id"));
				root.setText(d.getStr("name"));
				treeList.add(root);
			}
		}

		return treeList;
	}
	
	public boolean isleaf(String pid) {
		return getNumByParentId(pid) == 0;
	}
	
	public int getNumByParentId(String pid) {
		String sql = "select id from t_menu where parent_id = '" + pid
				+ "' ";
		List<Record> list = Db.find(sql);
		if (list != null && list.size() > 0) {
			return list.size();
		}
		return 0;
	}
}
